<template>
  <JeepayBackground :bgColorStyle="{ height: '776rpx' }">
    <JeepayCustomNavbar textColor="#fff" bgDefaultColor="linear-gradient(270deg, rgba(72, 192, 255, 1) 0%, rgba(51, 157, 255, 1) 100%)" title="码牌" backCtrl="back" />

    <JeepayTableListItem
      viewClass="list-item-by-detail"
      logo="/pageDevice/static/detailsLislImg/code-white.svg"
      :title="vdata.record.qrcAlias"
      :subtitle="vdata.record.qrcId"
      :moreBtnList="list"
    />

    <view class="create-time">
      <view class="time-title">创建时间</view>
      <view class="time-info">{{ vdata.record.updatedAt }}</view>
    </view>
    <JeepayCard editText="编辑信息" @editTap="toEdit">
      <JeepayDescviewItem title="码牌名称" :desc="vdata.record.qrcAlias" />
      <JeepayDescviewItem title="码牌金额" :desc="vdata.record.fixedFlag == 1 ? '固定金额' : '任意金额'" />
      <JeepayDescviewItem title="绑定门店" :desc="vdata.record.storeName" />
      <JeepayDescviewItem title="绑定应用" :desc="vdata.record.appName" />
    </JeepayCard>
    <JDetailsSwitch title="设备状态" subTitle="状态禁用后，该设备将无法使用">
      <template #titleRight>
        <JeepayStateSwitch v-model:state="vdata.record.qrcState" :showSwitchType="true" :updateStateFunc="confirmState" />
      </template>
    </JDetailsSwitch>
    <JeepayCard>
      <view class="qr-code flex-center">
        <image class="qr-code-img" :src="vdata.qrcImgUrl" mode="scaleToFill" />
      </view>
      <template #editContent>
        <view class="card-edit flex-center" hover-class="touch-hover" @tap="downLoadImg">
          <image style="width: 40rpx; height: 40rpx; margin-right: 10rpx" src="/pageDevice/static/devIconImg/icon-save.svg" mode="scaleToFill" /> 保存至相册
        </view>
      </template>
    </JeepayCard>
    <JeepayCard viewStyle="margin-top:30rpx" title="受支持的云喇叭设备" subtitle="以下云喇叭设备将会播报来自当前码牌的订单">
      <block v-for="v in hornList" :key="v.deviceNo">
        <hornCard :flag="v.state == 1" :title="v.deviceName" :subTitle="v.deviceNo" />
      </block>
    </JeepayCard>
  </JeepayBackground>
  <JSinglePopup ref="more" :list="list" activeColor="#FF5B4C" />
  <JeepayPopupConfirm ref="tips" />
</template>

<script setup>
import { reactive, ref } from 'vue'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import hornCard from './components/hornCard.vue'
import go from '@/commons/utils/go.js'
import { reqLoad, API_URL_SYS_CODE_LIST, $getHornList, $unBindQrc } from '@/http/apiManager.js'
import qrCode from '@/commons/utils/qrCode.js'
import { saveHeadImgFile } from '@/commons/utils/saveImg.js'
import infoBox from '@/commons/utils/infoBox.js'
import emit from '@/commons/utils/emit.js'
onLoad((options) => {
  getDetails(options.codeId)
  uni.$on(emit.ENAME_REF_QRC_DETAIL, () => {
    getDetails(vdata.record.qrcId)
  })
})
onUnload(() => uni.$off(emit.ENAME_REF_QRC_DETAIL))
const more = ref(null)
const tips = ref(null)
const params = {}
const vdata = reactive({
  record: {},
})
const hornList = reactive([])
const list = reactive([
  { label: '保存二维码图片', value: 'save', fun: downLoadImg },
  { label: '解除绑定', value: 'remove', color: '#FF5B4C', fun: unBinding },
])
function unBinding() {
  more.value.close()
  tips.value
    .open('确认解除绑定吗？', { confirmColor: '#FF5B4C' })
    .then((res) => {
      if (vdata.record.qrcBelongType == 1) return infoBox.showErrorToast('自建码牌不能解绑')
      $unBindQrc(vdata.record.qrcId).then((res) => {
        infoBox.showSuccessToast('解绑成功')
        go.back(1, emit.ENAME_REF_QRC_LIST)
      })
    })
    .catch((err) => {
      more.value.open('remove')
    })
}
const getDetails = (id) => {
  reqLoad.getById(API_URL_SYS_CODE_LIST, id).then(({ bizData }) => {
    vdata.record = bizData
    vdata.qrcImgUrl = qrCode.drawImg(bizData.qrUrl)
    getHornList(id)
  })
}
// 查询受支持的云喇叭设备
const getHornList = (id) => {
  $getHornList(id).then(({ bizData }) => {
    Object.assign(hornList, bizData.records)
    console.log('hornList', hornList)
  })
}
const confirmState = (bol) => {
  console.log('bol', bol)
  return reqLoad.addOrUpdate(vdata.record.qrcId, API_URL_SYS_CODE_LIST, { qrcState: bol }).then((res) => {
    emit.refPageAndSearchEmit(emit.ENAME_REF_QRC_LIST)
  })
}
// 保存二维码
function downLoadImg() {
  // #ifdef  APP-PLUS
  saveHeadImgFile(vdata.qrcImgUrl, 80)
    .then((success) => {
      infoBox.showSuccessToast('保存成功')
    })
    .catch((err) => {
      infoBox.showErrorToast('保存失败')
    })
  // #endif
  //#ifdef MP-WEIXIN
  downloadQR()
  //#endif
}
//#ifdef MP-WEIXIN
function downloadQR() {
  wx.getSetting({
    //获取权限
    success(res) {
      if (res.authSetting['scope.writePhotosAlbum']) {
        download(vdata.qrcImgUrl)
      } else {
        wx.authorize({
          scope: 'scope.writePhotosAlbum',
          success() {
            download(vdata.qrcImgUrl)
          },
        })
      }
    },
  })
}
function download(data) {
  const fileManager = wx.getFileSystemManager()
  const filePath = wx.env.USER_DATA_PATH + '/res.png'
  //这块是定义图片的名称，可自定义其他
  fileManager.writeFile({
    filePath: filePath,
    data: data.slice(22),
    encoding: 'base64',
    success: (res) => {
      wx.saveImageToPhotosAlbum({
        filePath: filePath,
        success: function (res) {
          //保存成功
          infoBox.showSuccessToast('保存成功')
        },
        fail: function (err) {
          console.log(err)
          //保存失败
          infoBox.showErrorToast('保存失败')
        },
      })
    },
    fail: (err) => {
      infoBox.showErrorToast('保存失败')
    },
  })
}
//#endif
const toEdit = (val) => {
  go.to('PAGES_APP_CODE_BIND', { codeId: vdata.record.qrcId })
}
</script>

<style lang="scss" scoped>
.create-time {
  display: flex;
  justify-content: space-between;
  margin: 0 75rpx;
  padding: 50rpx 0;
  font-size: 30rpx;
  border-top: 1rpx solid rgba(255, 255, 255, 0.2);
  .time-title {
    color: rgba(255, 255, 255, 0.7);
  }
  .time-info {
    color: #fff;
  }
}
.store-info {
  padding: 0.1rpx;
  margin: 0 35rpx;
  background-color: #fff;
  border-radius: $J-b-r32;
}
.default-img {
  width: 50rpx;
  height: 50rpx;
}

.qr-code {
  width: 680rpx;
  height: 370rpx;
  .qr-code-img {
    width: 270rpx;
    height: 270rpx;
  }
}
.c-card-wrapper {
  margin-top: 30rpx !important;
}
.card-edit {
  height: 110rpx;
  border-top: 1rpx solid #ededed;
  color: #2980fd;
  font-size: 33rpx;
  font-weight: 400;
  image {
    width: 44rpx;
    height: 44rpx;
    margin-right: 10rpx;
  }
}
</style>
